package com.jy.project.service.imp;

import cn.hutool.Hutool;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.jy.project.domain.User;
import com.jy.project.dto.LoginDTO;
import com.jy.project.ex.BizException;
import com.jy.project.service.LoginService;
import com.jy.project.service.UserService;
import com.jy.project.util.JwtUtils;
import com.jy.project.util.RedisUtils;
import com.jy.project.vo.LoginVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;

    @Autowired
    RedisUtils redisUtils;

    public  static  final  String LOGIN_KEY="login:key:";
    @Override
    public LoginVO login(LoginDTO dto) {
        if (StringUtils.isEmpty(dto.getUserName())){
            throw  new BizException("用户名不能为空");
        }
        if (StringUtils.isEmpty(dto.getPwd())){
            throw  new BizException("密码不能为空");
        }
        User user = userService.getUser(dto.getUserName());
        if (user==null){
            throw  new BizException("账户不存在");
        }
        String pwd = dto.getPwd();
        String md5Str = SecureUtil.md5(pwd).toUpperCase();

        if ( !md5Str.equals(user.getPwd())){
            throw  new BizException("密码错误");
        }
        if (user.getStatus()==0){
            throw  new BizException("账户审核中");
        }
        if (user.getStatus()==2){
            throw  new BizException("账户审核未通过");
        }
        LoginVO loginVO =new LoginVO();
        BeanUtils.copyProperties(user,loginVO);
        String sign = JwtUtils.sign(user);
        loginVO.setToken(sign);
        String key=LOGIN_KEY+user.getId();
        redisUtils.set(key,sign,60*60*72);
        return loginVO;
    }

    public static void main(String[] args) {
        String md5Str = SecureUtil.md5("Syx#123456").toUpperCase();

        System.out.println(md5Str);
    }
}
